package com.example.demo.component;

import com.example.demo.common.ApplicationVariable;
import com.example.demo.common.IpFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import static com.example.demo.controller.UserController.BLACKLIST_MAP;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-06-07
 * Time: 8:56
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 检查是否在黑名单中
        if (BLACKLIST_MAP.containsKey(request.getRemoteAddr())) {
            long blackTime = BLACKLIST_MAP.get(request.getRemoteAddr());
            if (System.currentTimeMillis() < blackTime) {
                // 还在黑名单中
                response.sendRedirect("位于黑名单中, 请联系管理员或十分钟后再尝试");
                return false;
            } else {
                // 已经超过黑名单时间，移出黑名单
                BLACKLIST_MAP.remove(request.getRemoteAddr());
            }
        }

        // 判断用户登陆
        HttpSession session = request.getSession(false);

        // 用户登录拦截
        if (session != null && session.getAttribute(ApplicationVariable.SESSION_USERINFO_KEY) != null) {
            return true; // 走后续代码
        }

        response.sendRedirect("/login3.html");
        return false;

}


}